package com.yunzhou.controller.user;

import com.yunzhou.constants.Constants;
import com.yunzhou.constants.RedisConstants;
import com.yunzhou.dto.EmailDTO;
import com.yunzhou.dto.UserLoginDTO;
import com.yunzhou.dto.UserRegisterDTO;
import com.yunzhou.entity.UserInfo;
import com.yunzhou.properties.JwtProperties;
import com.yunzhou.result.Result;
import com.yunzhou.service.ImageCheckCodeService;
import com.yunzhou.service.MinioService;
import com.yunzhou.service.UserService;

import com.yunzhou.utils.MyStringUtil;
import com.yunzhou.utils.ThreadLocalUtil;
import com.yunzhou.vo.UserDetailVO;
import com.yunzhou.vo.UserLoginVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/user/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private ImageCheckCodeService imageCheckCodeService;
    @Resource
    private MinioService minioService;
    @Resource
    private StringRedisTemplate stringRedisTemplate; // redis
    @Resource
    private JwtProperties jwtProperties;

    // 前端获取 登录用的 图片验证码
    @GetMapping("/getLoginImageCheckCode")
    public void getImageCheckCode(HttpServletResponse response, HttpSession session) throws IOException {
        imageCheckCodeService.getImageCheckCode(response, session, Constants.LOGIN_IMAGE_CHECK_CODE);
    }

    // 登录
    @PostMapping("/login")
    public Result login(HttpSession session, @RequestBody @Validated UserLoginDTO userLoginDTO){
        System.out.println("登录参数为：" + userLoginDTO);
        UserLoginVO userLoginVO = userService.login(session, userLoginDTO.getEmail(), userLoginDTO.getPassword(), userLoginDTO.getImageCheckCode());
        return Result.success(userLoginVO);
    }

    // 前端获取 注册用的 图片验证码
    @GetMapping("/getRegisterImageCheckCode")
    public void getRegisterImageCheckCode(HttpServletResponse response, HttpSession session) throws IOException {
        imageCheckCodeService.getImageCheckCode(response, session, Constants.REGISTER_IMAGE_CHECK_CODE);
    }

    // 发送发送邮件用的 邮箱验证码
    @GetMapping("/sendRegisterEmailCheckCode")
    public Result sendRegisterEmailCheckCode(HttpSession session, @Validated EmailDTO emailDTO){
        System.out.println("发送邮箱验证码（注册用）"+emailDTO);
        userService.sendRegisterEmailCheckCode(session, emailDTO.getEmail(), emailDTO.getImageCheckCode());
        return Result.success();
    }

    // 注册
    @PostMapping("/register")
    public Result register(HttpSession session, @RequestBody UserRegisterDTO userRegisterDTO){
        System.out.println("注册参数为：" + userRegisterDTO);
        userService.register(session, userRegisterDTO.getEmail(), userRegisterDTO.getEmailCheckCode(),
            userRegisterDTO.getPassword(), userRegisterDTO.getImageCheckCode());
        return Result.success();
    }

    // 获取用户详细信息
    @GetMapping("/getUserDetail")
    public Result<UserDetailVO> getUserDetail(Long userId){
        UserDetailVO userDetailVO = userService.getUserDetail(userId);
        return Result.success(userDetailVO);
    }

    // 根据Token获取用户信息
    @GetMapping("/getUserInfoByToken")
    public Result getUserInfoByToken() {
        UserInfo userInfo = userService.selectByUserId(ThreadLocalUtil.getCurrentUserId());
        return Result.success(userInfo);
    }

    // 上传用户头像
    @PostMapping("/uploadUserAvatar")
    public Result uploadUserAvatar(HttpServletRequest request, @RequestBody MultipartFile file){
        // 这里打算用UUID生成文件名
        String uuid = MyStringUtil.getUUID();
        // 文件名为UUID+文件名后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //.png
        String imgName = uuid + suffix;
        System.out.println("文件名为：" + imgName);

        String imagePath = null;
        try {
            imagePath = minioService.uploadFile(file , Constants.MINIO_USER_AVATAR_BUCKET_NAME, imgName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 先修改数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(ThreadLocalUtil.getCurrentUserId());
        userInfo.setAvatar(imagePath);
        userService.updateUserInfo(userInfo);

        // 再修改Redis
        String token = request.getHeader(jwtProperties.getTokenName());
        String tokenKey = RedisConstants.LOGIN_TOKEN_KEY + token;
        stringRedisTemplate.opsForHash().put(tokenKey, "avatar", imagePath);

        return Result.success(imagePath);
    }

    // 更新用户信息
    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(HttpServletRequest request, @RequestBody UserInfo userInfo){
        userInfo.setUserId(ThreadLocalUtil.getCurrentUserId());
        userService.updateUserInfo(userInfo);

        // 再修改Redis
        String token = request.getHeader(jwtProperties.getTokenName());
        String tokenKey = RedisConstants.LOGIN_TOKEN_KEY + token;
        stringRedisTemplate.opsForHash().put(tokenKey, "nickname", userInfo.getNickname());

        return Result.success();
    }

    // 登出

}
